//
//  PictureView.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/9.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import SDWebImage

private let PictureCellId = "PictureCellId"
private let PictureCellMargin: CGFloat = 5
class PictureView: UICollectionView {
    
    var picName:String?{
        didSet{
//            picNames.removeAll()
//            for _ in 0..<random()%10{
//                //随机出来有多少,就有多少次添加,为0则不进来
//                picNames.append(picName!)
//            }
//            print("图片",picName,"有",picNames.count,"个")
            //MARK: 刷新数据并且更新约束
            reloadData()
            let viewSize=ViewSize()
            self.snp_updateConstraints { (make) in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
        }
    }
    var picURLs:[NSURL]=[]{
        didSet{
            reloadData()
            let viewSize=ViewSize()
            self.snp_updateConstraints { (make) in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
        }
    }
    
    //MARK: 估计视图大小
    
    func ViewSize() -> CGSize {
        //获取最大宽度
        let MaxWidth=SCREENSIZE.width-2*cellMargin
        //计算出单张图片的宽度
        let picWidth=(MaxWidth-2*PictureCellMargin)/3
        //设置cell的大小
        let layout=self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize=CGSizeMake(picWidth, picWidth)
        
        let imageCount = picURLs.count ?? 0
        //根据图片的多少返回SGSize
        if imageCount==0{
            return CGSizeZero
        }
        //默认是一张
//        if imageCount==1{
//            print("picURLs",picURLs)
//            let key = picURLs.last?.absoluteString
//            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
//            print(key)
//            print(image)
//            let imageSize=image.size
//            
//            //        layout.itemSize=CGSizeMake(MaxWidth*0.8, MaxWidth*0.8*imageSize.height/imageSize.width)
//            layout.itemSize=imageSize
//            return imageSize
//        }
        //行数
        let row = lroundf(Float(picURLs.count)/3.0-0.51)+1
        return CGSizeMake(MaxWidth, picWidth*CGFloat(row)+(CGFloat(row)-1)*PictureCellMargin)
        //        1 2 3 -> 1
        //        4 5 6 -> 2
        //        7 8 9 -> 3
        
    }
    
    //MARK: 初始化
    
    init(){
        //初始化布局
        let layOut=UICollectionViewFlowLayout()
        //设置布局的间距
        layOut.minimumInteritemSpacing=PictureCellMargin
        layOut.minimumLineSpacing=PictureCellMargin
        //父类初始化
        super.init(frame: CGRectZero, collectionViewLayout: layOut)
        //注册类
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        //设置自己为数据代理源
        self.dataSource=self
        //搭建界面
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        backgroundColor = UIColor.whiteColor()
    }
}

//MARK: 数据代理
extension PictureView :UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
        cell.name=picURLs[indexPath.row]
        return cell
    }
}

class PictureCell :UICollectionViewCell{
    var name:NSURL?{
        didSet{
            imageView.sd_setImageWithURL(name, placeholderImage: UIImage(named: "avatar_default_big"))
        }
    }
    
    //MARK: 父类方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI
    func setupUI(){
        //添加子控件
        addSubview(imageView)
        //设置样式
        imageView.snp_updateConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //MARK: 懒加载控件
    lazy var imageView:UIImageView={
        //初始化一个
        let iv=UIImageView()
        //设置样式
        iv.contentMode = .ScaleAspectFill
        //        //手写代码,必须自己手动添加 剪裁
        iv.clipsToBounds=true
        return iv
    }()
}
